<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-card>
      <SearchForm
        :form-option="formOption"
        :show-btn="true"
        :btn-list="btnList"
        layout="column"
        v-model="formOption.formData"
        label-width="90px"
      />
    </el-card>

    <!-- tab栏 start -->
    <Tabs :tabs="tabs" :currentKey="currentKey" @tab-click="tabClick">
      <div>
        <el-button type="primary" size="medium" @click="toAdd">新增商品</el-button>
        <el-button size="medium" @click="exportFileByEmail" :loading="allLoading"
          >导出全部</el-button
        >
      </div>
    </Tabs>
    <div class="mb-10">
      <el-button type="" @click="doWayBatch(true)">批量上架</el-button>
      <el-button type="" @click="doWayBatch(false)">批量下架</el-button>
    </div>
    <!-- tab栏 end -->

    <!-- 数据表格 start -->
    <el-card class="card">
      <PageTable
        ref="table"
        :loading="loading"
        :data="dataSource"
        :columns="columns"
        :options="options"
        @selectChange="selectChange"
      />
      <Pagination
        v-show="total > 0"
        :total="total"
        :pageNo.sync="listQuery.pageNo"
        :pageSize.sync="listQuery.pageSize"
        @pagination="getGoodsList"
      />
    </el-card>
    <!-- 数据表格 end -->

    <!-- 导出全部 -->
    <SelectEmail v-model="SelectEmailDialog" :type="exportType" @exportAll="handleExportAll" />

    <!-- 修改商品名称 -->
    <UpdateGoodsName
      v-model="UpdateGoodsNameDialog"
      v-if="UpdateGoodsNameDialog"
      ref="updateGoodsName"
      @update="getGoodsList"
    />
  </div>
</template>

<script>
import { downLoadImg } from '@/hooks'
import UpdateGoodsName from '@/views/goods/goods-list/components/UpdateGoodsName'
import {
  OPEN_PLATFORM,
  RECOMMMEND_STATUS,
  PLATFORM_COLOR,
  GOODS_TYPE,
  ON_THE_SHELF_STATUS
} from '@/enum/goods.js'
import { REGISTER_PLATFORM_SELECT } from '@/enum/user'
export default {
  name: 'GoodsList',
  components: { UpdateGoodsName },
  data() {
    return {
      // 表单搜索配置
      formOption: {
        items: [
          {
            type: 'input',
            label: '商品名称',
            value: 'name'
          },
          {
            type: 'daterange',
            label: '新增时间',
            value: 'addTime',
            valueFormat: 'yyyy-MM-dd'
          },
          {
            type: 'input',
            label: '兑换积分',
            placeholder: '请输入积分值',
            value: 'minPrice'
          },
          {
            type: 'input',
            label: '至',
            placeholder: '请输入积分值',
            labelWidth: '40px',
            value: 'maxPrice'
          },
          {
            type: 'select',
            label: '上架状态',
            value: 'sellType',
            clearable: true,
            selectList: ON_THE_SHELF_STATUS
          },
          {
            type: 'select',
            label: '所属分类',
            value: 'categoryOneId',
            placeholder: '请选择一级分类',
            selectList: []
          },
          {
            type: 'select',
            value: 'categoryTwoId',
            placeholder: '请选择二级分类',
            selectList: []
          },
          {
            type: 'select',
            value: 'categoryThreeId',
            placeholder: '请选择三级分类',
            selectList: []
          },
          {
            type: 'select',
            label: '推荐状态',
            value: 'isSortCategory',
            clearable: true,
            selectList: RECOMMMEND_STATUS
          },
          {
            type: 'select',
            label: '推荐到首页状态',
            value: 'isSortHome',
            labelWidth: '125px',
            clearable: true,
            selectList: RECOMMMEND_STATUS
          },
          {
            type: 'select',
            label: '上架平台',
            value: 'platform',
            clearable: true,
            selectList: REGISTER_PLATFORM_SELECT
          },
          {
            type: 'input',
            label: '成本价',
            placeholder: '请输入成本价',
            value: 'minCostPrice'
          },
          {
            type: 'input',
            label: '至',
            placeholder: '请输入成本价',
            labelWidth: '40px',
            value: 'maxCostPrice'
          },
          {
            type: 'select',
            label: '供应商',
            value: 'supplierId',
            labelWidth: '80px',
            style: {
              width: '210px'
            },
            selectList: []
          }
        ],
        formData: {
          sellType: '',
          platform: '',
          isSortHome: '',
          isSortCategory: '',
          categoryOneId: '',
          categoryTwoId: '',
          categoryThreeId: ''
        }
      },
      SelectEmailDialog: false,
      UpdateGoodsNameDialog: false,
      exportType: 2,

      // 表单按钮列表
      btnList: [
        {
          type: 'primary',
          label: '筛选',
          onClick: () => {
            this.doSearch()
          }
        },
        {
          label: '重置',
          onClick: () => {
            for (let key in this.formOption.formData) {
              this.formOption.formData[key] = ''
            }
            this.doSearch()
          }
        }
      ],
      // 当前激活tab
      currentKey: '',
      tabs: [
        {
          key: '',
          label: '全部',
          field: 'total',
          num: 0
        },
        {
          key: '2',
          label: '已上架',
          field: 'totalSelling',
          num: 0
        },
        {
          key: '3',
          label: '在仓库',
          field: 'totalNotSell',
          num: 0
        },
        {
          key: '1',
          label: '已售罄',
          field: 'totalSellFinished',
          num: 0
        }
      ],

      // 分页配置
      listQuery: {
        pageNo: 1,
        pageSize: 10
      },
      total: 0,

      // 表格加载
      loading: false,
      // 导出全部加载
      allLoading: false,
      // 表格配置
      options: {
        border: true,
        select: true
      },
      // 表格列
      columns: [
        {
          label: '商品名称',
          width: '160px',
          render: (h, { row }) => {
            return (
              <div style={'display: flex'}>
                <div class="flex flex-col">
                  <el-image
                    style={'width: 60px;height: 60px;'}
                    src={row.mainGraph}
                    preview-src-list={[row.mainGraph]}
                  />
                  <el-popover
                    placement="bottom"
                    title="商品二维码"
                    width="200"
                    trigger="click"
                    onHide={() => {
                      this.showQrCode = ''
                    }}
                  >
                    <div class="flex-col flex align-center">
                      {this.showQrCode ? (
                        <img style={'width: 85px;height: 85px;'} src={this.showQrCode} />
                      ) : (
                        <span>加载中...</span>
                      )}

                      <p class="mt-5">扫码后直接访问商品</p>
                      <el-link
                        class="mt-5 ft-12"
                        underline={false}
                        type="primary"
                        onClick={() => this.downLoadQr(row.goodsName)}
                      >
                        下载二维码
                      </el-link>
                    </div>
                    <el-link
                      class="ft-12"
                      underline={false}
                      type="primary"
                      slot="reference"
                      onClick={() => this.getQrcode(row)}
                    >
                      商品二维码
                    </el-link>
                  </el-popover>
                </div>
                <div class="flex flex-col justify-between">
                  <div class="goodsNameClass ml-5" style="color:#409eff">
                    {row.name}
                  </div>
                  <el-link
                    class="ft-12"
                    underline={false}
                    type="primary"
                    slot="reference"
                    onClick={() => this.updateGoodsName(row)}
                  >
                    修改名称
                  </el-link>
                </div>
              </div>
            )
          }
        },
        {
          label: '商品分类',
          render: (h, { row }) => {
            return <div>{row.category}</div>
          }
        },
        {
          label: '销售价格',
          width: '160px',
          render: (h, { row }) => {
            const isDiff = row.maxPrice === row.minPrice
            const isMoneyDiff = row.minMoney === row.maxMoney
            return (
              <div>
                <div>
                  {isDiff ? row.minPrice : `${row.minPrice}-${row.maxPrice}`}
                  {row.priceType == 2 ? '积分' : ''}
                </div>
                {row.priceType == 2 ? (
                  <div>
                    {isMoneyDiff ? `￥${row.minMoney}` : `￥${row.minMoney}-${row.maxMoney}`}
                  </div>
                ) : (
                  ''
                )}
                <p>{row.priceType == 2 ? '积分+现金' : '纯积分'}</p>
              </div>
            )
          }
        },
        {
          label: '成本价',
          render: (h, { row }) => {
            const isDiff = row.maxCostPrice === row.minCostPrice
            return (
              <div>{isDiff ? row.minCostPrice : `${row.minCostPrice}-${row.maxCostPrice}`}</div>
            )
          }
        },
        {
          prop: 'minPrice',
          label: '兑换积分',
          render: (h, { row }) => {
            const isDiff = row.maxPrice === row.minPrice
            return <div>{isDiff ? row.minPrice : `${row.minPrice}-${row.maxPrice}`}</div>
          }
        },
        {
          label: '库存',
          render: (h, { row }) => {
            let element = !row.verifyStock ? (
              <div>暂无</div>
            ) : (
              <div class="flex-col justify-center">
                <p>{row.validStockQuantity}</p>
                {row.validStockQuantity <= row.stockWarningQuantity ? (
                  <p style="color:#fc4560">{row.validStockQuantity <= 0 ? '已售罄' : '库存不足'}</p>
                ) : (
                  ''
                )}
              </div>
            )
            return element
          }
        },
        { prop: 'sort', label: '排序值' },
        {
          label: '供应商',
          render: (h, { row }) => {
            return <div>{row.supplierName}</div>
          }
        },
        {
          label: '商品类型',
          render: (h, { row }) => {
            return (
              <div>
                <p>{GOODS_TYPE[row.type]}</p>
                {row.type === 3 ? <p>{`${row.supplyName}供应链`}</p> : ''}
              </div>
            )
          }
        },
        { prop: 'createdTime', label: '新增时间' },
        {
          label: '上架平台',
          render: () => {
            return (
              <div class="flex flex-col">
                {Object.keys(OPEN_PLATFORM).map(el => (
                  <el-tag size="small" color={PLATFORM_COLOR[el]} style="color:#fff" class="mt-5">
                    {OPEN_PLATFORM[el]}
                  </el-tag>
                ))}
              </div>
            )
          }
        },
        {
          label: '上架状态',
          render: (h, { row }) => {
            return (
              <div>
                {Object.keys(OPEN_PLATFORM).map(el => (
                  <el-switch
                    class="custom-switch mt-10"
                    value={row.platformState.includes(el)}
                    active-text="已上架"
                    inactive-text="仓库中"
                    active-color={PLATFORM_COLOR[el]}
                    inactive-color="#9b9b9f"
                    v-on:change={() => this.changeOpenStatus(row, el)}
                  ></el-switch>
                ))}
              </div>
            )
          }
        },
        {
          label: '操作',
          width: '160px',
          render: (h, { row }) => {
            return (
              <div class="flex-col flex align-center">
                <div>
                  <el-link
                    class="mr-5"
                    underline={false}
                    type="primary"
                    onClick={() => this.toEdit(row)}
                  >
                    编辑
                  </el-link>
                  <PopConfirm
                    id={row.id}
                    title={'确定删除该商品吗？'}
                    confirm={() => this.deleteGoods(row)}
                  >
                    <el-link underline={false} type="primary">
                      删除
                    </el-link>
                  </PopConfirm>
                </div>

                <el-link
                  type={row.isSortHome ? '' : 'primary'}
                  underline={false}
                  onClick={() => this.setRecom('isSortHome', row)}
                >
                  {row.isSortHome ? '取消首页推荐' : '首页推荐'}
                </el-link>
                <el-link
                  underline={false}
                  type={row.isSortCategory ? '' : 'primary'}
                  onClick={() => this.setRecom('isSortCategory', row)}
                >
                  {row.isSortCategory ? '取消推荐' : '推荐'}
                </el-link>
              </div>
            )
          }
        }
      ],
      // 表格源数据
      dataSource: [],
      // 选择列表数据
      selectList: [],
      // 展示的商品二维码地址
      showQrCode: ''
    }
  },
  watch: {
    // 监听一级分类设置
    'formOption.formData.categoryOneId'(value) {
      this.formOption.formData.categoryTwoId = ''
      this.formOption.formData.categoryThreeId = ''
      const blackList = ['categoryTwoId', 'categoryThreeId']
      this.formOption.items = this.formOption.items.map(el => {
        const newEl = this.$lodash.cloneDeep(el)
        if (blackList.includes(newEl.value)) {
          newEl.selectList = []
        }
        return newEl
      })
      if (value) {
        this.getClassifyList(value, 'categoryTwoId')
      }
    },

    // 监听二级分类设置
    'formOption.formData.categoryTwoId'(newValue) {
      this.formOption.items = this.formOption.items.map(el => {
        const newEl = this.$lodash.cloneDeep(el)
        if (newEl.value === 'categoryThreeId') {
          newEl.selectList = []
        }
        return newEl
      })
      this.formOption.formData.categoryThreeId = ''
      if (newValue) {
        this.getClassifyList(newValue, 'categoryThreeId')
      }
    }
  },
  activated() {
    this.getGoodsList()
  },
  created() {
    this.getSuplier()
    this.getClassifyList()
    this.getGoodsList()
  },
  methods: {
    //修改商品名称
    updateGoodsName(row) {
      this.UpdateGoodsNameDialog = true
      this.$nextTick(() => {
        this.$refs.updateGoodsName.initData(row)
      })
    },
    // 导出全部
    async exportFileByEmail() {
      this.$confirm(
        '确定要导出全部吗？数据量较大会导出较慢，请耐心等待。请勿重复点击，如出现导出失败，请联系技术部门。',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(async () => {
          this.SelectEmailDialog = true
        })
        .catch(err => err)
    },
    // 获取商品列表
    async getGoodsList() {
      this.loading = true
      try {
        // 参数整合
        const params = {
          ...this.listQuery,
          ...this.formOption.formData,
          startCreateTime: this.formOption.formData?.addTime?.[0] ?? '',
          endCreateTime: this.formOption.formData?.addTime?.[1] ?? ''
        }
        delete params.addTime
        // 发送请求
        const { data } = await this.$http.goods.goods.page({ params })
        this.dataSource = data.records
        this.total = data.total
        // tabs数据赋值
        this.tabs = this.tabs.map(el => ({ ...el, num: data[el.field] }))
        this.loading = false
      } catch (error) {
        this.loading = false
      }
    },

    // 导出全部
    async handleExportAll(value) {
      const params = {
        email: value,
        ...this.formOption.formData,
        startCreateTime: this.formOption.formData?.addTime?.[0] ?? '',
        endCreateTime: this.formOption.formData?.addTime?.[1] ?? ''
      }
      delete params.addTime
      this.allLoading = true

      const res = await this.$http.goods.goods.excelExport({ params })
      if (res.status == 200) {
        this.$message.success('导出成功')
        this.allLoading = false
      }
    },

    // 搜索
    doSearch() {
      this.currentKey = ''
      this.listQuery.pageNo = 1
      this.getGoodsList()
    },

    /**
     * 批量上下架操作
     * @param {Boolean} state 是否上架 true-上架 false-下架
     */
    doWayBatch(state) {
      if (!this.selectList.length) {
        this.$message.error('请勾选商品后操作')
        return
      }
      this.$http.goods.goods
        .batchEnablePlatform({
          state,
          ids: this.selectList.map(el => el.id),
          platform: '2'
        })
        .then(res => {
          if (res.status === 200) {
            this.$message.success('操作成功')
            this.getGoodsList()
          }
        })
        .catch(err => {
          console.log('doWayBatch', err)
        })
    },

    /**
     * 点击新增商品
     */
    toAdd() {
      this.$router.push({ name: 'GoodsMangeAdd' })
    },

    /**
     * 点击编辑
     * @param {Object} row  当前行数据
     */
    toEdit({ id }) {
      this.$router.push({ name: 'GoodsMangeEdit', query: { id } })
    },

    // tab切换
    tabClick({ key }) {
      this.listQuery.pageNo = 1
      this.currentKey = key
      this.formOption.formData.sellType = Number(key) || ''
      this.getGoodsList()
    },

    /**
     * 勾选列表行数据
     * @parma {Array} rows 选中行
     */
    selectChange(rows) {
      this.selectList = rows
    },

    /**
     * 点击查看商品二维码
     * @param {Object} row  当前行数据
     */
    async getQrcode({ id }) {
      const { data } = await this.$http.goods.goods.createQrcodeById({
        autoColor: true,
        goodsId: id,
        isHyaline: true,
        lineColor: { r: '0', g: '0', b: '0' },
        page: '',
        width: 280
      })
      this.showQrCode = data
    },

    // 点击下载二维码
    downLoadQr(name) {
      downLoadImg(name, this.showQrCode)
    },

    /**
     * 删除商品
     * @param {Object} row  当前行数据
     */
    deleteGoods({ id }) {
      this.$http.goods.goods
        .delete(id)
        .then(res => {
          if (res.status === 200) {
            this.$message.success('删除成功')
            this.getGoodsList()
          }
        })
        .catch(err => {
          console.log('deleteGoods', err)
        })
    },

    /**
     * 设置平台启用状态
     * @param {Object} row  当前行数据
     * @param {String} value 当前状态
     */
    changeOpenStatus({ id, platformState }, value) {
      // 当前状态是否激活
      const isOpen = platformState.includes(value)
      // 参数处理
      let platformParma = null
      if (isOpen) {
        platformParma = platformState
          .split(',')
          .filter(el => el !== value && el)
          .join(',')
      } else {
        platformParma = platformState
          .split(',')
          .concat([value])
          .filter(el => el)
          .join(',')
      }
      // 发送请求
      const message = isOpen ? '已隐藏' : '已开启'
      this.$http.goods.goods
        .enablePlatform({ id, platform: platformParma })
        .then(() => {
          this.getGoodsList()
          this.$message.success(message)
        })
        .catch(err => {
          console.log('changeOpenStatus', err)
        })
    },

    /**
     * 设置商品推荐
     * @param {String} key isSortCategory:是否推荐到列表 isSortHome:是否推荐到首页
     * @param {Object} item 当前行数据
     */
    setRecom(key, item) {
      const api = {
        isSortCategory: 'recommendCategory',
        isSortHome: 'recommendHome'
      }
      this.$http.goods.goods[api[key]](item.id, !item[key])
        .then(res => {
          console.log(res)
          if (res.status === 200) {
            const tip = item[key] ? '已取消推荐' : '已推荐'
            this.$message.success(tip)
            this.getGoodsList()
          }
        })
        .catch(err => {
          console.log('setRecom', err)
        })
    },

    // 获取分类列表
    async getClassifyList(parentId = 0, key = 'categoryOneId') {
      try {
        const { data } = await this.$http.goods.classify.getByParentId({ params: { parentId } })
        this.formOption.items = this.formOption.items.map(el => {
          const newEl = this.$lodash.cloneDeep(el)
          if (newEl.value === key) {
            newEl.selectList = data.map(el => ({ ...el, label: el.name, value: el.id }))
          }
          return newEl
        })
      } catch (error) {
        console.log('getClassifyList', error)
      }
    },
    // 获取供应商列表
    async getSuplier() {
      const { data } = await this.$http.goods.supplier.list()
      this.formOption.items = this.formOption.items.map(item => {
        if (item.value === 'supplierId') {
          item.selectList = data.map(ele => {
            return {
              value: ele.id,
              label: ele.name
            }
          })
        }
        return item
      })
    }
  }
}
</script>

<style lang="scss" scope>
.goodsNameClass {
  @include ellipsis(4);
}
</style>
